<!-- 短剧授权 -->
<!-- 短剧授权 -->
<template>
  <el-dialog v-model="dialogVisible" width="480" title="" draggable appendToBody destroyOnClose lockScroll :closeOnClickModal="false">
    <base-skeleton v-if="pageLoad.loadState === true" style="width: 100%; height: 100%; min-height: 420px; padding: 0 20px"></base-skeleton>
    <template v-else-if="pageLoad.loadState === false">
      <el-form ref="elFormRef" v-auto-animate v-AutoAnimate :model="formData" :rules="rules" scrollToError :disabled="disabled">
        <el-form-item label="授权平台" labelWidth="8em" prop="platform">
          <box-from-border>
            <el-radio-group v-model="formData.platform" @change="platformChange">
              <el-radio v-for="item in mpList" :key="item.value" :label="item.label" :value="item.value"></el-radio>
            </el-radio-group>
          </box-from-border>
        </el-form-item>
        <el-form-item key="form-item-1" label="小程序" labelWidth="8em" prop="socialId">
          <bubble-select-local
            v-model="formData.socialId"
            labelKey="appName"
            valueKey="appCode"
            :list="miniProgramListCpt"
            placeholder="请选择小程序"
          ></bubble-select-local>

        </el-form-item>


        <el-form-item key="form-item-1" label="短剧变现类型" labelWidth="8em" prop="iaaType">
          <bubble-select-local
              v-model="formData.iaaType"
              labelKey="name"
              valueKey="code"
              :list="iaaTypeList"
              placeholder="请选择短剧变现类型"
          ></bubble-select-local>
        </el-form-item>


        <el-form-item v-if="!disabled" key="el-form-item-4" labelWidth="0em">
          <div style="width: 100%; padding-top: 20px">
            <el-button style="width: 100%" type="success" :disabled="loading" :loading="loading" @click="submit">保存</el-button>
          </div>
        </el-form-item>
      </el-form>
    </template>
    <base-empty
      v-else
      style="height: 100%"
      :description="pageLoad.description || ''"
      :imageSize="240"
      :loadState="pageLoad.loadState"
      :pageLoadButton="[{ text: '重新加载', callBack: getBaseDataAxios }]"
    ></base-empty>
  </el-dialog>
</template>

<script setup lang="ts">
  import type { CheckboxValueType, FormInstance, FormRules } from 'element-plus';
  import IconEpLoading from '~icons/ep/loading';
  import IconEpArrowUp from '~icons/ep/arrow-up';
  import { vAutoAnimate } from '@formkit/auto-animate/vue';
  import { type MpInfo, getMpInfoAxios } from '@/api/marketing-management';
  import { type MiniProgramListItem, getMiniProgramList } from '@/api/app-management';
  import { dramaAuth, getUnSkitLicensing,DramaReal } from '@/api/drama-management';
  import { filterRepeat } from '@/utils/data.ts';

  const pageLoad = shallowReactive<$PageLoad>({ loadState: false, description: '' });

  const dialogVisible = ref(false);
  const elFormRef: Ref<FormInstance | null> = ref(null);
  const action = ref<'add' | 'details' | 'edit'>();
  const loading = ref(false);
  const notAuthDramaListLoading = ref(false);
  const notAuthDramaList = ref<{ dramaId: number; dramaTitle: string }[]>([]);
  const mpInfoLIst = shallowRef<MpInfo[]>([]);
  const checkAll = ref(false);
  const indeterminate = ref(false);
  const disabled = computed(() => action.value === 'details');

  const props = defineProps({
    list: {
      type:Array,
      default: () => []
    },
  })


  const formData = reactive({
    dramaIds: [] as number[],
    socialId: '',
    platform: 'mp-weixin',
  });

  type _MiniProgramListItem = Pick<MiniProgramListItem, 'appName' | 'socialId' | 'type'> & {};

  const miniProgramList = ref<_MiniProgramListItem[]>([]);

  const miniProgramListCpt = computed<_MiniProgramListItem[]>(() => miniProgramList.value.filter((v) => v.type === formData.platform));

  const rules = computed(() => {
    const _rules: FormRules<any> = {
      platform: [{ required: true, type: 'string', message: '请选择授权平台', trigger: ['blur', 'change'] }],
      socialId: [{ required: true, type: 'string', message: '请选择小程序', trigger: ['blur', 'change'] }],
      iaaType: [{ required: true, type: 'number', message: '请选择短剧变现类型', trigger: ['blur', 'change'] }],
    };
    return _rules;
  });

  const iaaTypeList=ref([
    {
      name:"纯IAA",
      code:1,

    },
    {
      name:"纯IAP",
      code:2,
    },
    {
      name:"IAAP混合变现",
      code:3,
    }
  ])

  /**
   * 提交
   */
  async function submit() {
    try {
      await elFormRef.value?.validate();
      try {
        loading.value = true;
        // if (formData.platform === 'mp-weixin') {
        //   formData.dramaIds = [];
        // }

        console.log(props.list)

        await DramaReal({
          dramaIdList: props.list.map(item=>{
            return item.dramaId
          }),
          appCode: formData.socialId,
          iaaType:Number(formData.iaaType),
        });


        ElToast.success('授权成功');
        loading.value = false;
        hide();
      } catch (error) {
        loading.value = false;
        ElToast.error(error.msg || '授权失败，-BD001');
      }
    } catch (error) {
      ElToast.error('提交失败，请完善表单，-BD002');
    }
  }



  /** 清除已选小程序 */
  function platformChange() {
    formData.socialId = '';
    formData.dramaIds = [];
    notAuthDramaList.value = [];
  }

  watch(
    () => formData.dramaIds,
    (val) => {
      if (val.length === 0) {
        checkAll.value = false;
        indeterminate.value = false;
      } else if (val.length === notAuthDramaList.value.length) {
        checkAll.value = true;
        indeterminate.value = false;
      } else {
        indeterminate.value = true;
      }
    }
  );

  const handleCheckAll = (val: CheckboxValueType) => {
    indeterminate.value = false;
    if (val) {
      formData.dramaIds = notAuthDramaList.value.map((_) => _.dramaId);
    } else {
      formData.dramaIds = [];
    }
  };

  /**
   * 显示
   */
  function show() {
    formData.platform = 'mp-weixin';
    formData.dramaIds = [];
    formData.socialId = '';
    getBaseDataAxios();
    dialogVisible.value = true;
  }

  /**
   * 隐藏
   */
  function hide() {
    dialogVisible.value = false;
  }

  const mpList = computed(() => {
    const list: { label: string; value: string; investmentId: number; iaaFlag: 0 | 1 }[] = [];
    mpInfoLIst.value.forEach((item) => {
      if (item.platformType !== 'mp-kuaishou') {
        list.push({ label: item.platformName, value: item.platformType, investmentId: item.investmentId!, iaaFlag: item.iaaFlag });
      }
    });

    console.log( filterRepeat(list, 'value')," filterRepeat(list, 'value')")


    return [filterRepeat(list, 'value').find(at=>{
      return at.value == 'mp-weixin'
    })];
  });

  /** 请求 */
  async function getBaseDataAxios() {
    try {
      pageLoad.loadState = true;

      const res = await getMiniProgramList({ current: 1, size: 100 });
      miniProgramList.value = res.data.records ?? [];

      const { data } = await getMpInfoAxios();
      mpInfoLIst.value = data;

      pageLoad.loadState = false;
    } catch (error) {
      miniProgramList.value = [];
      pageLoad.loadState = 'err';
      pageLoad.description = String((error as Record<string, unknown>).msg || '') || '获取数据失败';
    }
  }

  defineExpose({ show, hide });
</script>
